<template>
  <div class="project">
    <ListTab v-if="!showMobilePage" :mode="1" :mode-list="modeList" show-header />
    <div :class="{'mobile-table mobile-min-height mobile-el-dialog-form':showMobilePage}" class="table-list min-fill-page">
      <div v-if="!showMobilePage" class="relative mb16 filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <i v-if="batchLoading" class="el-icon-loading mr5"/>
        <MoreOpeator
          v-if="showMore"
          ref="moreOpeatorRef"
          :list="moreOperatorList"
          style="margin-right:10px;"
        />
      </div>
      <div v-loading="listLoading" class="table-wrap">
        <u-table
          v-if="list.items.length > 0"
          ref="tableRef"
          :data="list.items"
          :row-class-name="tableRowClassName"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="false"
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable">
          <u-table-column
            :fixed="selectFixed"
            align="center"
            type="selection"
            width="50"/>
          <u-table-column align="left" label="客户联系人">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.contactPerson" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="联系方式" min-width="150">
            <template slot-scope="scope">
              <ToolTip v-if="scope.row.showSecret" :content="scope.row.tel" />
              <div v-else>
                <span v-if="scope.row.tel.length <= 2">***********</span>
                <span v-else>{{ `${scope.row.tel[0]}*********${scope.row.tel[scope.row.tel.length - 1]}` }}</span>
                <el-button type="text" style="color: #406EFF; font-size: 14px" @click="handleView(scope.row)">点击查看</el-button>
              </div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                :disabled="!hasRouteAuth('crm:customer:edit')"
                active-color="#406EFF"
                inactive-color="#cccccc"
                @change="switchStatus(scope.row, $event)"
              />
            </template>
          </u-table-column>
          <u-table-column align="left" label="协作人">
            <template slot-scope="scope">
              <CheckUserInfo
                v-if="scope.row.associate && scope.row.associate.length"
                :user-list="scope.row.associate"
                :multiple="scope.row.associate.length > 1"
                :user-id="scope.row.associate.length === 1?scope.row.associate[0].id:null"
                :label="scope.row.associate.length === 1?scope.row.associate[0].userName:null"
                label-name="userName"
              />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="协作部门">
            <template slot-scope="scope">
              <ToolTip :content="formatName(scope.row.coDepartment, 'name')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="客户名称">
            <template slot-scope="scope">
              <el-tooltip :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.clientName }}</div>
                <span class="light-word ellipsisOne" @click="toDetail(scope.row)">{{ scope.row.clientName }}</span>
              </el-tooltip>
            </template>
          </u-table-column>
          <u-table-column label="创建人">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.creatorId" :user-id="scope.row.creatorId" :label="scope.row.creator" />
              <ToolTip v-else :content="scope.row.creator" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="所属部门">
            <template slot-scope="scope">
              <ToolTip :content="formatName(scope.row.department, 'name')" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="120">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">{{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm:ss') }}</div>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="备注">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.remark" />
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" :align="operateAlign" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" class="flex">
                <div v-if="hasRouteAuth('crm:customer:edit')" class="button-text" @click="handleEdit(scope.row)">编辑</div>
                <span v-if="hasRouteAuth('crm:customer:edit') && showDel(scope.row)" class="btn-line" />
                <div v-if="showDel(scope.row)" class="button-text" @click="handleDelete(scope.row)">删除</div>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item v-if="hasRouteAuth('crm:customer:edit')" style="width:90px;text-align: center" @click.native="handleEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="showDel(scope.row)" style="width:90px;text-align: center" @click.native="handleDelete(scope.row)">
                  <div>删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination>
        <template v-if="!showMobilePage">
          <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
          <div style="flex: 1;" />
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
        <template v-else>
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
          <MoreOpeator
            v-if="showMore"
            ref="moreOpeatorRef"
            :list="moreOperatorList"
            show-mobile-icon
          />
        </template>
      </fixed-pagination>
    </div>
    <setContactDialog ref="setContactDialog" @updateList="updateList()"/>
    <AddContactDialog ref="AddContactDialog" :customer-id="rowClientId" @updateDetail="fetchData(true)"/>
  </div>
</template>

<script>
import { batchDelete, deleteContact, checkClientPhone, getContactList, editContactStatus } from '@/api/customer';
import { getDepartmentAll } from '@/api/config';
import ListTab from '@/components/ListTab';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import setContactDialog from '../module/setContactDialog';
import AddContactDialog from '../detail/module/addContactDialog';
import { standardFormat } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import ElMessage, { showModal } from '@/utils/message';
import { formatName } from '@/utils/tools';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { mapState } from 'vuex';

export default {
  components: {
    ListTab,
    EmptyPlaceholder,
    MoreOpeator,
    setContactDialog,
    AddContactDialog
  },
  filters: { standardFormat },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  data() {
    return {
      isUmyTable: true,
      listLoading: false,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      paramsObj: {},
      departmentOption: [],
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      ids: '',
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }],
      batchLoading: false,
      arrayKeyArr: ['coDepartmentId'],
      rowClientId: 0
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    modeList() {
      return [
        { mode: 0, name: '客户', handleClick: this.goCustomerPage },
        { mode: 1, name: '联系人', handleClick: () => {} }
      ];
    },
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'contactPerson', name: '客户联系人', labelWidth: '90px', type: 'input' },
        { keyword: 'clientName', name: '客户名称', labelWidth: '90px', type: 'input' },
        { keyword: 'associate', name: '协作人', labelWidth: '90px', type: 'inputSearch', tagName: 'associateName' },
        { keyword: 'creator', name: '创建人', labelWidth: '90px', type: 'input' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '90px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'coDepartmentId', name: '协作部门', type: 'cascaderSelectWithChild', childrenVal: 'children',
          options: this.departmentOption }
      ];
      return arr;
    },
    showMore() {
      return this.hasRouteAuth('crm:customer:setAssociate') || this.hasRouteAuth('crm:customer:setCooDepartment') || this.hasRouteAuth('crm:customer:batchDelete');
    },
    moreOperatorList() {
      return [
        { label: '设置协作人', handelClick: this.setAssociate, auth: this.hasRouteAuth('crm:customer:setAssociate') },
        { label: '批量删除', handelClick: this.batchDelete, disabled: this.batchLoading, auth: this.hasRouteAuth('crm:customer:batchDelete') }
      ];
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 150 : 0;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'loanDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isChange) {
      this.paramsObj = {};
      this.fetchData(true);
      this.queryDeptTreeList();
    } else {
      // this.page = localStorage.getItem('projectPage');
      if (this.list && this.list.items && this.list.items.length === 0) {
        this.fetchData(true);
      } else {
        this.fetchData();
      }
    }
  },
  methods: {
    hasRouteAuth,
    formatName,
    goCustomerPage() {
      this.$router.push('customer');
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.departmentOption = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    formatParams(sendPageConfig = true) {
      const { page, perPage, paramsObj } = this;
      const params = JSON.parse(JSON.stringify(paramsObj));
      // 设置tab
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (sendPageConfig) {
        params.page = page;
        params.perPage = perPage;
      }
      return params;
    },
    fetchData(reset = false) {
      if (!hasRouteAuth('crm:customer:contactsInfo:read')) return;
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.listLoading = true;
      getContactList(params).then(({ data = {}} = {}) => {
        data.items.map(item => {
          item.showSecret = false;
          return item;
        });
        this.list = data;
      }).catch(e => {
        console.error(e);
      }).finally(() => {
        this.list.isInit = false;
        this.listLoading = false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(perPage) {
      this.perPage = perPage;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    showDel(row) {
      return this.$store.getters.userName === row.creator || this.hasRouteAuth('crm:customer:deleteContact');
    },
    handleView(row) {
      checkClientPhone(row.id).then(() => {
        row.showSecret = true;
      });
    },
    // 检查是否勾选
    cheCkSelect() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择所需操作的联系人');
        return false;
      }
      const ids = this.multipleSelectionAll.map(el => el.id).join(',');
      return ids;
    },
    batchDelete() {
      if (!this.cheCkSelect()) { return; }
      const ids = this.cheCkSelect();
      showModal('请确认是否删除所选内容', '', {}).then(_ => {
        this.batchLoading = true;
        batchDelete({ ids }).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$message.success('删除成功');
          // 删除后查看当前页是否有数据，没有则页数-1
          if (this.multipleSelectionAll.length === this.list.items.length && this.page > 1) {
            this.page -= 1;
          }
          this.fetchData();
          this.clearMixinSelection();// 清除选中
          this.batchLoading = false;
        }).catch(err => {
          this.batchLoading = false;
          console.log(err);
        });
      }).catch(_ => null);
    },
    updateList() {
      this.clearMixinSelection();// 清除选中
      this.fetchData();
    },
    setAssociate() {
      if (!this.cheCkSelect()) { return; }
      const ids = this.cheCkSelect();
      this.$refs.setContactDialog.openDialog(ids, 0);
    },
    setCooDepartment() {
      if (!this.cheCkSelect()) { return; }
      const ids = this.cheCkSelect();
      this.$refs.setContactDialog.openDialog(ids, 1);
    },
    handleEdit(row) {
      this.rowClientId = Number(row.clientId);
      this.$refs.AddContactDialog.openDialog(row);
    },
    handleDelete(row) {
      showModal('请确认是否删除所选内容', '', {}).then(_ => {
        this.batchLoading = true;
        deleteContact(row.id).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功！');
            // 删除后查看当前页是否有数据，没有则页数-1
            if (this.list.items.length === 1 && this.page > 1) {
              this.page -= 1;
            }
            this.fetchData();
          }
          this.batchLoading = false;
        }).catch(err => {
          this.batchLoading = false;
          console.log(err);
        });
      }).catch(_ => null);
    },
    toDetail(item) {
      const routeUrl = this.$router.resolve({
        name: 'detailCustomer',
        params: { customerId: item.clientId }
      });
      window.open(routeUrl.href, '_blank');
    },
    switchStatus(row, status) {
      showModal(`请确认是否${status ? '启用' : '禁用'}该联系人？`, '', {}, true).then(_ => {
        editContactStatus(row.id, status).then(res => {
          if (res.code === 200) {
            ElMessage.success('操作成功');
            this.fetchData();
          }
        }).catch(_ => {
          row.status = status ? 0 : 1;
        });
      }).catch(_ => {
        row.status = status ? 0 : 1;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.project {
  & ::v-deep {
    .mode-switch-container {
      box-shadow: none !important;
    }
  }
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .filter {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      position: relative;
    }
    .flex {
      display: flex;
      align-items: center;
      .button-text {
        &:first-of-type{
          margin-right: 8px;
        }
        &:last-of-type{
          margin-left: 8px;
        }
      }
    }
    .btn-line {
      height: 14px;
      border-right: 1px solid #ddd;
    }
  }
}
.el-icon-loading{
  font-size: 14px;
}
.light-word {
  color: #406eff;
  cursor: pointer;
}
</style>
